const MAX_LIMIT = 2;

const sendRequest = (requestList = [], callback) => {
  const promises = requestList.slice();
  let limit = Math.min(MAX_LIMIT, requestList.length);

  const runTaskNeeded = () => {
    let i = 0;
    while (i < limit) {
      i++;
      runTask();
    }
  };

  // 取出任务并且执行任务
  const runTask = () => {
    const task = promises.shift();

    task && runner(task);
  };

  // 执行器
  const runner = async (task) => {
    try {
      limit++;
      await task();
    } catch (error) {
    } finally {
      limit--;
      picker();
    }
  };

  const picker = () => {
    // 执行剩余任务
    if (limit < MAX_LIMIT && promises.length > 0) {
      runTask();
    } else if (promises.length === 0 && limit === 0) {
      callback && callback();
    }
  };

  runTaskNeeded();
};

const request = (url, timer = 1000) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("请求结束：" + url);
      resolve("success");
    }, timer);
  });
};

sendRequest(
  [
    () => request("1"),
    () => request("2"),
    () => request("3"),
    () => request("4"),
    () => request("5"),
    () => request("6"),
    () => request("7"),
    () => request("8"),
    () => request("9"),
  ],
  (res) => console.log(res)
);
